<script setup lang="ts">
import {getAPI} from "@/api/MyAxiosAPI";
import {onBeforeMount, onBeforeUnmount, reactive, ref} from 'vue'
import type {CalendarVO, NoteInterface, ResponseInterface, TaskInterface} from "@/type/models";
import {getNoteInfoById} from "@/api/NoteAPI";
import {getTaskById} from "@/api/project/TaskAPI";
import NotePreview from "@/components/Note/NotePreview.vue";
import ClipboardJS from "clipboard";
import {getKeyAPI, resetKeyAPI, subscribeURL} from "@/api/ICSAPI";
import {ElMessage} from "element-plus";

const MOCK = false;
const API = getAPI(MOCK)
const TOKEN: string = localStorage.getItem("token") as string
const value = ref(new Date())
let calendarList = ref<Array<CalendarVO>>([])

function getCalendarListAPI() {
    API({
        url: '/ics/calendar',
        method: 'get',
        headers: {
            Authorization: localStorage.getItem("token")
        }
    }).then(res => {
        let r: ResponseInterface = res.data;
        calendarList.value = r.data
        // 奖calendarList中每个元素的start属性实例化为date
        calendarList.value.forEach(item => {
            item.start = new Date(item.start)
        })
    })
}

//------抽屉
let drawer = ref(false)
const noteAndTaskList = reactive<Array<NoteInterface | TaskInterface>>([])

let activeName = ref('0')

async function openDrawer(day: any) {
    drawer.value = true
    let month = day.split('-')[1]
    let day_ = day.split('-')[2]
    let tempList = []
    for (let i = 0; i < calendarList.value.length; i++) {
        if (calendarList.value[i].start.getMonth() + 1 == month && calendarList.value[i].start.getDate() == day_) {
            tempList.push(calendarList.value[i])
        }
    }
    console.log(tempList)
    let resultList: Array<NoteInterface | TaskInterface> = []
    for (let i = 0; i < tempList.length; i++) {
        if (tempList[i].type == "NOTE") {
            let r: ResponseInterface = await getNoteInfoById(tempList[i].id, TOKEN)
            if (r.code == 200) {
                resultList.push(r.data)
            }
        }
        if (tempList[i].type == "TASK") {
            let r: ResponseInterface = await getTaskById(tempList[i].id, TOKEN)
            if (r.code == 200) {
                resultList.push(r.data)
            }
        }
    }
    //清空noteAndTaskList
    noteAndTaskList.push(...resultList)
}

function closeDrawer() {
    drawer.value = false
    noteAndTaskList.splice(0, noteAndTaskList.length)
}

function date2String(date: Date | string) {
    if (typeof date === 'string') {
        date = new Date(date);
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

//------end 抽屉
//------ics key 以及订阅
let icsKey = ref('')
let loadKey = ref(false)
let copyURL: any = undefined

async function getKey() {
    loadKey.value = true
    const r: ResponseInterface = await getKeyAPI(TOKEN)
    if (r.code == 200) {
        icsKey.value = r.data
        if (icsKey.value === "" || icsKey.value == null) {
            await resetKey()
        }
        loadKey.value = false
    }
}

async function resetKey() {
    loadKey.value = true
    const r: ResponseInterface = await resetKeyAPI(TOKEN)
    if (r.code == 200) {
        icsKey.value = r.data
        loadKey.value = false
    }
}

//------end ics key 以及订阅
// 挂载
onBeforeMount(() => {
    getCalendarListAPI();
    getKey()
    if (copyURL == undefined) {
        copyURL = new ClipboardJS("#copyURL")
            .on('success', () => {
                ElMessage.success('复制成功');
                // 可以在此处添加提示用户复制成功的UI反馈
            }).on('error', (e) => {
                ElMessage.error('复制失败:', e);
                // 可以在此处添加提示用户复制失败的UI反馈
            });
    }
})
onBeforeUnmount(() => {
    if (copyURL != undefined) {
        copyURL.destroy()
        copyURL = undefined
    }
})
</script>

<template>
    <p>
        <el-button :loading="loadKey" id="copyURL" :data-clipboard-text="subscribeURL + icsKey">
            复制订阅链接
        </el-button>
        <el-popconfirm
            width="200"
            @confirm="resetKey"
            confirm-button-text="确定重置"
            cancel-button-text="取消"
            title="重置订阅链接后，之前的订阅链接将永久失效。"
        >
            <template #reference>
                <el-button>重置订阅链接</el-button>
            </template>
        </el-popconfirm>
    </p>
    <el-calendar v-model="value">
        <template #date-cell="{ data }">
            <p class="day">{{ data.day.split('-')[2] }}</p>
            <ul class="task-ul">
                <li class="task-li" v-for="item in calendarList" :key="item.id">
                    <!--对比item.start的日期和data.day的日期,item.start的月份和data.day的月份是否相等，相等则显示item.title-->
                    <div @click="openDrawer(data.day)"
                         v-if="item.start.getDate() == data.day.split('-')[2] && item.start.getMonth()+1 == data.day.split('-')[1]">
                        {{ item.title }}
                    </div>
                </li>
            </ul>
        </template>
    </el-calendar>
    <el-drawer
        v-model="drawer"
        title="列表"
        direction="rtl"
        :before-close="closeDrawer"
    >
        <el-collapse v-model="activeName" accordion>
            <el-collapse-item :title="item.name != undefined ? '任务:'+item.name : '备忘录:'+item.title" :name="index"
                              v-for="(item,index) in noteAndTaskList" :key="index">
                <div v-if="item.alarmTime != undefined">
                    <span>提醒时间：{{ date2String(item.alarmTime) }}</span>
                    <p style="margin: 0px">内容：</p>
                    <NotePreview :content="item.content" :note-id="item.noteId"></NotePreview>
                </div>
                <div v-else>
                    <el-descriptions :column="2" border title="任务详情">
                        <el-descriptions-item label="任务名称">{{ item.name }}</el-descriptions-item>
                        <el-descriptions-item label="任务状态">
                            <el-tag v-if="item.status == 0" type="success">准备中</el-tag>
                            <el-tag v-else-if="item.status == 1" type="warning">进行中</el-tag>
                            <el-tag v-else-if="item.status == 2" type="info">已完成</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="开始时间">{{
                                date2String(item.beginTime.toLocaleString())
                            }}
                        </el-descriptions-item>
                        <el-descriptions-item label="结束时间">{{
                                date2String(item.endTime.toLocaleString())
                            }}
                        </el-descriptions-item>
                        <el-descriptions-item label="任务内容">{{ item.description }}</el-descriptions-item>
                    </el-descriptions>
                </div>
            </el-collapse-item>
        </el-collapse>
    </el-drawer>
</template>

<style scoped>
.day {
    margin: 0;
    padding: 0;
}

.task-li {
    list-style-type: none;

}

.task-ul {
    margin: 0;
    padding: 0;
}
</style>